package com.yps.io.aio.client;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

public class ReadHandler implements CompletionHandler<Integer, ByteBuffer> {

	//用于读半包消息和发送应答
	private AsynchronousSocketChannel channel;
	private CountDownLatch latch;
	public ReadHandler( AsynchronousSocketChannel channel) {
		this.channel  = channel;
	}
	
	public ReadHandler(AsynchronousSocketChannel channel, CountDownLatch latch) {
		// TODO Auto-generated constructor stub
		this.channel = channel;
		this.latch = latch;
	}

	//读取消息后的处理
	@Override
	public void completed(Integer result, ByteBuffer attachment) {
		//flip操作
		attachment.flip();
		//根据attachment大小创建字节码数组
		byte[] message = new byte[attachment.remaining()];
		//读取数据
		attachment.get(message);
		try {
			String expression = new String(message, "UTF-8");
			System.out.println("客户端收到的消息为：" + expression);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void failed(Throwable exc, ByteBuffer attachment) {
		try {
			System.out.println("读取请求失败");
			channel.close();
			latch.countDown();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	

}
